import logging
import os
import sys

import click
import httpx
import uvicorn

from a2a.server.apps import A2AStarletteApplication
from a2a.server.request_handlers import DefaultRequestHandler
from a2a.server.tasks import (
    BasePushNotificationSender,
    InMemoryPushNotificationConfigStore,
    InMemoryTaskStore,
)
from a2a.types import (
    AgentCapabilities,
    AgentCard,
    AgentSkill,
)
# from dotenv import load_dotenv
from agent_.process.agent import ProcessAgent
from agent_.process.agent_executor import ProcessAgentExecutor


# load_dotenv()

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class MissingAPIKeyError(Exception):
    """Exception for missing API key."""


@click.command()
@click.option('--host', 'host', default='localhost')
@click.option('--port', 'port', default=10000)
def main(host, port):
    """Starts the Currency Agent server."""
    try:
        # if os.getenv('model_source', 'google') == 'google':
        #     if not os.getenv('GOOGLE_API_KEY'):
        #         raise MissingAPIKeyError(
        #             'GOOGLE_API_KEY environment variable not set.'
        #         )
        # else:
        #     if not os.getenv('TOOL_LLM_URL'):
        #         raise MissingAPIKeyError(
        #             'TOOL_LLM_URL environment variable not set.'
        #         )
        #     if not os.getenv('TOOL_LLM_NAME'):
        #         raise MissingAPIKeyError(
        #             'TOOL_LLM_NAME environment not variable not set.'
        #         )

        capabilities = AgentCapabilities(streaming=True, push_notifications=True)
        skill = AgentSkill(
            id='convert_currency',
            name='流程治理平台',
            description='流程治理平台与各系统对接接口规范相关知识',
            tags=['流程治理平台', '接口规范'],
            examples=['流程治理平台与各系统对接接口规范'],
        )
        agent_card = AgentCard(
            name='问智宝',
            description='这个智能体是一个能够回答流程治理平台相关知识的机器，它可以通过自然语言理解技术理解用户的问题，并通过知识库或搜索引擎找到最佳答案。它能够不断学习，提高回答的准确性和速度，为用户提供更好的服务。',
            url=f'http://{host}:{port}/',
            version='1.0.0',
            default_input_modes=ProcessAgent.SUPPORTED_CONTENT_TYPES,
            default_output_modes=ProcessAgent.SUPPORTED_CONTENT_TYPES,
            capabilities=capabilities,
            skills=[skill],
        )


        # --8<-- [start:DefaultRequestHandler]
        # httpx_client = httpx.AsyncClient()
        # push_config_store = InMemoryPushNotificationConfigStore()
        # push_sender = BasePushNotificationSender(httpx_client=httpx_client,
        #                 config_store=push_config_store)
        request_handler = DefaultRequestHandler(
            agent_executor=ProcessAgentExecutor(),
            task_store=InMemoryTaskStore(),
            # push_config_store=push_config_store,
            # push_sender= push_sender
        )
        server = A2AStarletteApplication(
            agent_card=agent_card, http_handler=request_handler
        )

        uvicorn.run(server.build(), host=host, port=port)
        # --8<-- [end:DefaultRequestHandler]

    except MissingAPIKeyError as e:
        logger.error(f'Error: {e}')
        sys.exit(1)
    except Exception as e:
        logger.error(f'An error occurred during server startup: {e}')
        sys.exit(1)


if __name__ == '__main__':
    main()
